package cn.wolfcode.ssm.shiro;

import cn.wolfcode.ssm.util.JSONResult;
import cn.wolfcode.ssm.util.JSONUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component("extendFormFilter")
public class ExtendFormFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSONUtil.toJSONString(new JSONResult()));

        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        response.setContentType("text/json;charset=UTF-8");
        JSONResult result = new JSONResult();
        result.mark("用户名或密码有误");

        try {
            response.getWriter().write(JSONUtil.toJSONString(request));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}